A complex regular expression is one that exhibits several or all of the following characteristics. It can be quite lengthy, containing multiple
nested or repeated groups, numerous alternations, extensive use of backreferences and escape characters, lookaheads, lookbehinds, and other advanced
features. Additionally, complex regular expressions may lack proper comments and documentation, making them challenging to comprehend and maintain.
Overly complicated regular expressions are hard to read and maintain and can easily cause hard-to-find bugs.
To determine the complexity of a regular expression, each of the following operators increases the complexity by an amount equal to the current
nesting level and also increases the current nesting level by one for its arguments:
Additionally, each use of a character
class and backreferences
increase the complexity by 1 regardless of nesting.
This rule will raise an issue when total complexity is above the threshold maxComplexity
(20 by default).
const datePattern = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/; //Noncompliant: move some validation logic to regular code
if (dateString.match(datePattern)) {
handleDate(dateString);
}
If a regex is too complicated, you should consider replacing (partially or completely) it with regular code. Alternatively, split it apart into
multiple patterns. If a regular expression is split among multiple variables, the complexity is calculated for each variable individually, not for the
whole regular expression.
const datePattern = /^\d{1,2}([-/.])\d{1,2}\1\d{1,4}$/;
if (dateString.match(datePattern)) {
const dateParts = dateString.split(/[-/.]/);
const day = parseInt(dateParts[0]);
const month = parseInt(dateParts[1]);
const year = parseInt(dateParts[2]);
// Put logic to validate and process the date based on its integer parts here
}